<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ id ? '编辑企业' : '添加企业' }}</span>
      </div>
      <div class="right">
        黑马程序员
      </div>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleForm" label-width="100px" :model="addForm" :rules="addRules">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :value="item.industryCode"
                  :label="item.industryName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <!-- action 必须的 上传文件到哪个服务器地址
                    show-file-list 是否显示已上传文件列表
                    on-success 文件上传成功的钩子函数
                    before-upload 文件上传前的钩子函数

                    :http-request="uploadFn"
                -->
              <el-upload
                class="avatar-uploader"
                action="https://api-hmzs.itheima.net/tj/upload"
                :show-file-list="false"
                :on-success="handleLicenseSuccess"
                :before-upload="beforeLicenseUpload"
                :headers="{Authorization:`Bearer ${$store.state.user.token}`}"
                :data="{type:'businessLicense'}"
                :http-request="uploadFn"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>

            </el-form-item>
          </el-form>
          <p v-show="id">在编辑状态下，默认图片是原图片，由于是下载url，所以不显示。下载地址：</p>
          <p v-show="id">{{ addForm.businessLicenseUrl }}</p>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button>重置</el-button>
        <el-button type="primary" @click="confirmAdd">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { createEnterpriseAPI, getEnterpriseDetailAPI, getIndustryListAPI, updateEnterpriseAPI, uploadAPI } from '@/apis/park'
export default {
  data() {
    return {
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      industryList: [], // 行业列表
      imageUrl: '', // 营业执照图片地址
      addRules: { // 表单验证规则
        name: [
          { required: true, message: '企业名称为必填', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '法人为必填', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '注册地址为必填', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '所在行业为必填', trigger: 'change' }
        ],
        contact: [
          { required: true, message: '企业联系人为必填', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '企业联系人电话为必填', trigger: 'blur' }
        ],
        businessLicenseId: [
          { required: true, message: '请上传营业执照', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  async created() {
    this.getIndustryList()
  },
  mounted() {
    this.addForm.name = '老李企业'
    this.addForm.legalPerson = '老李'
    this.addForm.registeredAddress = '地址' // 注册地址
    // this.addForm.industryCode = '' // 所在行业
    this.addForm.contact = '老李啊' // 企业联系人
    this.addForm.contactNumber = '13900002020' // 联系人电话
    // this.addForm.businessLicenseUrl = '' // 营业执照url
    // this.addForm.businessLicenseId = '' // 营业执照id
    // 有合同id 调用详情接口
    if (this.id) {
      this.getEnterpriseDetail()
      this.imageUrl = this.addForm.businessLicenseUrl
    }
  },
  methods: {
    // 获取行业列表
    async getIndustryList() {
      const res = await getIndustryListAPI()
      // console.log(res)
      this.industryList = res.data
    },
    // 营业执照上传成功的回调
    handleLicenseSuccess(res) {
      // console.log(res)
      // this.imageUrl = res.data.url
    },
    // 营业执照之前的回调
    beforeLicenseUpload(file) {
      const list = ['image/jpeg', 'image/png'] // MIME 媒体类型 (参考mdn) 是一种所有计算机软件共同遵守的一种媒体类型
      const isJPG = list.includes(file.type)
      const isLt3M = file.size / 1024 / 1024 < 3

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG / JPEG / PNG 格式!')
      }
      if (!isLt3M) {
        this.$message.error('上传头像图片大小不能超过 3MB!')
      }
      // console.log(isJPG && isLt3M)

      return isJPG && isLt3M
    },
    // 自定义上传过程 (upload 组件内有原生 AJAX 请求传递你选择的文件到action 指定后台接口)
    async uploadFn(fileObj) {
      const theFile = fileObj.file // file 文件类型对象
      // URL.createObjectURL 把文件数据流转成一个前端临时URL 地址纯前端预览的（文件 -> 地址）
      // this.imageUrl = URL.createObjectURL(theFile)

      // 调用接口，让服务器给我返回图片在服务器地址浏览
      // 文件对象 -> FormData，容器对象中 => 发给后台
      const fd = new FormData()
      fd.append('file', theFile)
      fd.append('type', 'businessLicense')
      const res = await uploadAPI(fd)
      console.log(res)
      this.imageUrl = res.data.url // 图片回显

      // 自己数据要手动关联到表单数据对象的属性中
      this.addForm.businessLicenseUrl = res.data.url
      this.addForm.businessLicenseId = res.data.id

      // 单独再对businessLicenseId进行校验
      this.$refs.ruleForm.validateField('businessLicenseId')
    }, // 新增企业-确定事件
    async confirmAdd() {
      await this.$refs.ruleForm.validate()
      // 校验通过，发起网络请求
      if (this.id) {
      // 编辑
        await updateEnterpriseAPI({
          ...this.addForm,
          id: this.id
        })
      } else {
      // 调用接口
        await createEnterpriseAPI(this.addForm)
      }
      // 返回列表页
      this.$router.back()
    },
    async getEnterpriseDetail() {
      const res = await getEnterpriseDetailAPI(this.id)
      const { businessLicenseId, businessLicenseUrl, contact,
        contactNumber, industryCode, legalPerson, name, registeredAddress } = res.data
      this.addForm = { businessLicenseId, businessLicenseUrl, contact,
        contactNumber, industryCode, legalPerson, name, registeredAddress }
      console.log(businessLicenseUrl)
    }
  }
}
</script>

<style scoped lang="scss">
  .add-enterprise {
    background-color: #f4f6f8;
    height: 100vh;

    .add-header {
      display: flex;
      justify-content: space-between;
      padding: 0 20px;
      height: 64px;
      line-height: 64px;
      font-size: 16px;
      font-weight: bold;
      background-color: #fff;

      .left {
        span {
          margin-right: 4px;
        }
        .arrow{
          cursor: pointer;
        }
      }

      .right {
        text-align: right;
      }
    }

    .add-main {
      background: #f4f6f8;
      padding: 20px 130px;

      .form-container {
        background-color: #fff;
        .title {
          height: 60px;
          line-height: 60px;
          padding-left:20px;
        }
        .form {
          margin-bottom: 20px;
          padding: 20px 65px 24px;
          .el-form{
            display: flex;
            flex-wrap: wrap;
            .el-form-item{
              width: 50%;
            }
          }
        }
      }
    }

    .add-footer {
      position: fixed;
      bottom: 0;
      width: 100%;
      padding: 24px 50px;
      color: #000000d9;
      font-size: 14px;
      background: #fff;
      text-align: center;
    }
  }
::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
::v-deep .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
::v-deep .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
::v-deep .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
